package com.practice.dao.daoImpl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import com.practice.dao.EmpDao;
import com.practice.entity.Emp;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * @author:高杰领
 * @date:2021/11/17 11:12
 * @description:通过spring JDBC实现的dao实现类
 * @version:1.0
 **/
@Data
@Repository
public class EmpDaoImpl implements EmpDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<Emp> selectAll() {
        String sql = " select * from Emp ";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        //查询为空无法转换
//        List<Emp> emps = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(Emp.class));
        List<Emp> empList = Convert.convert(new TypeReference<List<Emp>>() {
        }, list);
        return empList;
    }

    @Override
    public boolean insertEmp(Emp emp) {
        String sql = " insert into Emp values(?,?,?,?,?,?,?,?) ";
        Object[] params = {emp.getEMPNO(), emp.getENAME(), emp.getJOB(), emp.getMGR(), emp.getHIREDATE(), emp.getSAL(), emp.getCOMM(), emp.getDEPTNO()};
        int update = jdbcTemplate.update(sql, params);
        if (update > 0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean updateEmp(Emp emp) {
        String sql = " update Emp set ENAME=?,JOB=?,MGR=?,HIREDATE=?,SAL=?,COMM=?,DEPTNO=? where EMPNO=? ";
        Object[] params = {emp.getENAME(), emp.getJOB(), emp.getMGR(), emp.getHIREDATE(), emp.getSAL(), emp.getCOMM(), emp.getDEPTNO(), emp.getEMPNO()};
        int update = jdbcTemplate.update(sql, params);
        if (update > 0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean deleteEmp(int EMPNO) {
        String sql = " delete from Emp where EMPNO=? ";
        Object[] params = {EMPNO};
        int update = jdbcTemplate.update(sql, params);
        if(update>0){
            return true;
        }
        return false;
    }

    @Override
    public Emp selectOne(int EMPNO) {
        String sql = " select * from Emp where EMPNO=? ";
        Object[] params = {EMPNO};
        Map<String, Object> map = jdbcTemplate.queryForMap(sql, params);
        Emp emp = Convert.convert(new TypeReference<Emp>() {
        }, map);
        return emp;
    }
}
